package mail;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.Address;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMailSender {
	
	public static final JavaMailSender mailsender = new JavaMailSender();
	
    public void sendToMany(String smtpServer, Account account, String subject, String content, String[] to, String[] cc) {
        try {
            Session session = Session.getDefaultInstance(this.makeProperties(smtpServer), this.makeAuthenticator(account));
            
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(account.getUsername()));
            Address[] tos = new Address[to.length];
            for (int i = 0; i < to.length; i ++) {
            	tos[i] = new InternetAddress(to[i]);
            }
            mimeMessage.setRecipients(RecipientType.TO, tos);
            mimeMessage.setSubject(subject);
            mimeMessage.setText(content);
            
            Transport.send(mimeMessage);
        } catch (Exception ex) {
            Logger.getLogger(JavaMailSender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void send(String smtpServer, Account account, Message message) {
        try {
            Session session = Session.getDefaultInstance(this.makeProperties(smtpServer), this.makeAuthenticator(account));
            Transport.send(this.makeMimeMessage(session, message));
        } catch (Exception ex) {
            Logger.getLogger(JavaMailSender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private Properties makeProperties(String smtpServer) {
        Properties pros = new Properties();
        pros.put("mail.smtp.host", smtpServer);
        pros.put("mail.smtp.auth", "true");
        return pros;
    }

    private Authenticator makeAuthenticator(final Account account) {
        return new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(account.getUsername(), account.getPassword());
            }
        };
    }

    private MimeMessage makeMimeMessage(Session session, Message message) throws Exception {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(message.getFrom()));
        mimeMessage.setRecipient(RecipientType.TO, new InternetAddress(message.getTo()));
        mimeMessage.setSubject(message.getSubject());
        mimeMessage.setText(message.getContent());
        return mimeMessage;
    }
}